package com.dahua.ui.main;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.view.ViewCompat;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.dahua.R;
import com.dahua.adapters.GridAdapter;
import com.dahua.bean.Msg;
import com.dahua.bean.User;
import com.dahua.bean.VersionBean;
import com.dahua.ui.base.BaseActivity;
import com.dahua.ui.user.RegisterAct;
import com.dahua.utils.HttpUtils;
import com.dahua.utils.Tools;
import com.dahua.utils.UserPreference;
import com.dahua.utils.VersionChecker;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.HashMap;

import io.reactivex.functions.Consumer;


public class MainAct extends BaseActivity implements View.OnClickListener {
    EditText etName, etPwd;
    TextView tvMsg;
    GridView gv;
    String name[] = {"Scan", "Scan Record", "Project REG", "User Center", "My Message", "My Project"};
    int ids[] = {R.drawable.icon01, R.drawable.icon02, R.drawable.icon03, R.drawable.icon04, R.drawable.icon05, R.drawable.icon06};
    ArrayList<HashMap<String, Object>> item = new ArrayList<HashMap<String, Object>>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initView();
    }

    private void initView() {
//        Window window = getWindow();
        //设置透明状态栏,这样才能让 ContentView 向上
//        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
//        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        //设置状态栏颜色
//        window.setStatusBarColor(statusColor);
//        ViewGroup mContentView = (ViewGroup) findViewById(Window.ID_ANDROID_CONTENT);
//        View mChildView = mContentView.getChildAt(0);
//        if (mChildView != null) {
//            //注意不是设置 ContentView 的 FitsSystemWindows, 而是设置 ContentView 的第一个子 View . 使其不为系统 View 预留空间.
//            ViewCompat.setFitsSystemWindows(mChildView, false);
//        }
        etName = (EditText) findViewById(R.id.et_name);
        etPwd = (EditText) findViewById(R.id.et_pwd);
        tvMsg = (TextView) findViewById(R.id.tv_msg);
        gv = (GridView) findViewById(R.id.gv);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        showLoadingDialog();
        HttpUtils.getInstance().getMsgNum(handler, UserPreference.getInstance(getApplicationContext()).getUid());
        HttpUtils.getInstance().getVersion(handler);
    }

    public void login(View view) {
        String name = etName.getText().toString();
        String pwd = etPwd.getText().toString();
        if (name == null) {
            showToast("User name cannot be empty");
            return;
        }
        if (pwd == null) {
            showToast("Password cannot be empty");
            return;
        }
        showLoadingDialog();
        HttpUtils.getInstance().login(handler, name, pwd);
    }

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            hideLoadingDialog();
            switch (msg.what) {
                case 1:
                    item.clear();
                    Msg bean = (Msg) msg.obj;
                    if (bean.getModules().contains(",")) {
                        String m[] = bean.getModules().split(",");
                        for (int i = 0; i < m.length; i++) {
                            if ("1".equals(m[i])) {
                                HashMap<String, Object> map = new HashMap<String, Object>();
                                map.put("img", ids[0]);
                                map.put("name", name[0]);
                                item.add(map);
                            } else if ("2".equals(m[i])) {
                                HashMap<String, Object> map = new HashMap<String, Object>();
                                map.put("img", ids[1]);
                                map.put("name", name[1]);
                                item.add(map);
                            } else if ("3".equals(m[i])) {
                                HashMap<String, Object> map = new HashMap<String, Object>();
                                map.put("img", ids[2]);
                                map.put("name", name[2]);
                                item.add(map);
                            } else if ("4".equals(m[i])) {
                                HashMap<String, Object> map = new HashMap<String, Object>();
                                map.put("img", ids[3]);
                                map.put("name", name[3]);
                                item.add(map);
                            } else if ("5".equals(m[i])) {
                                HashMap<String, Object> map = new HashMap<String, Object>();
                                map.put("img", ids[4]);
                                map.put("name", name[4]);
                                item.add(map);
                            } else if ("6".equals(m[i])) {
                                HashMap<String, Object> map = new HashMap<String, Object>();
                                map.put("img", ids[5]);
                                map.put("name", name[5]);
                                item.add(map);
                            }
                        }
                    }
                    if(item.size()<=3){
                        HashMap<String, Object> map = new HashMap<String, Object>();
                        map.put("img", "");
                        map.put("name", "");
                        item.add(map);
                    }
                    gv.setAdapter(new GridAdapter(MainAct.this,item));
                    gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            HashMap<String, Object> map =item.get(position);
                            //String name[] = {"Scan", "Scan Record", "Project REG", "User Center", "My Message", "My Project"};
                            if("Scan".equals(map.get("name"))){
                                requestPermission();
//                                startActivity(new Intent(getApplicationContext(), MipcaActivityCapture.class));

                            }else if("Scan Record".equals(map.get("name"))){
                                Intent i = new Intent(getApplicationContext(), RegisterAct.class);
                                i.putExtra("url", "ScanRecord.html");
                                startActivity(i);
                            }else if("Project REG".equals(map.get("name"))){
                                Intent i = new Intent(getApplicationContext(), RegisterAct.class);
                                i.putExtra("url", "ProjectReg.html");
                                startActivity(i);
                            }else if("User Center".equals(map.get("name"))){
                                Intent i = new Intent(getApplicationContext(), RegisterAct.class);
                                i.putExtra("url", "user_center.html");
                                startActivity(i);
                            }else if("My Message".equals(map.get("name"))){
                                Intent i = new Intent(getApplicationContext(), RegisterAct.class);
                                i.putExtra("url", "message.html");
                                startActivity(i);
                            }else if("My Project".equals(map.get("name"))){
                                Intent i = new Intent(getApplicationContext(), RegisterAct.class);
                                i.putExtra("url", "MyProject.html");
                                startActivity(i);
                            }
                        }
                    });
//                    if(Integer.parseInt(count)>0){
//                        tvMsg.setVisibility(View.VISIBLE);
//                        tvMsg.setText(count);
//                    }else{
//                        tvMsg.setVisibility(View.GONE);
//                    }
                    break;
                case 2:
                    showToast(msg.obj.toString());
                    break;
                case 10:
                    VersionBean version= (VersionBean) msg.obj;
                    try {
                        if (Tools.getVersionCode(getApplicationContext()) <Integer.parseInt(version.getCode())) {
                            versionUpdateDialog(version);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    break;
            }
        }

        ;
    };

    private void versionUpdateDialog(final VersionBean bean) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Pending Updates");
        builder.setMessage("\nNew version has been released, please update now.\n");
        builder.setPositiveButton("Update Now", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                // AppTools.goToDownload(getApplicationContext(),
                // bean.getVersionDownloadUrl());
                new VersionChecker(MainAct.this).startUpdate(bean.getDownloadurl());
            }
        });
        builder.setNegativeButton("Do Not Update", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialoginterface, int i) {
                dialoginterface.dismiss();
            }
        });

        builder.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        }
    }

    private void requestPermission(){
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions
                .requestEach(Manifest.permission.CAMERA)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted){ //允许
                            startActivity(new Intent(getApplicationContext(), MipcaActivityCaptureZbar.class));//lzh
                        }else if (permission.shouldShowRequestPermissionRationale){//拒绝,期待下次询问
                            Toast.makeText(MainAct.this, "拒绝后无法使用该功能", Toast.LENGTH_SHORT).show();
                        }else {//拒绝,自行去设置界面
                            AlertDialog.Builder builder = new AlertDialog.Builder(MainAct.this);
                            builder.setTitle(" warning");
                            builder.setMessage("The user has rejected the permission and cannot use this function. Do you want to jump to the setting interface?");

                            // 拒绝, 退出应用
                            builder.setNegativeButton("cancel",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    });

                            builder.setPositiveButton("go to settings",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Intent intent = new Intent(
                                                    Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                            intent.setData(Uri.parse("package:" + getPackageName()));
                                            startActivityForResult(intent, 444);
                                        }
                                    });

                            builder.setCancelable(false);

                            builder.show();
                        }

                    }
                });
    }

}
